package com.ruoyi.classai.api;

import com.ruoyi.classai.domain.EwcChapter;
import com.ruoyi.classai.domain.dto.CourseAttendanceDto;
import com.ruoyi.classai.domain.dto.GroupDto;
import com.ruoyi.classai.domain.dto.GroupListDto;
import com.ruoyi.classai.domain.vo.LearningAnalytics.AnalyticsChapterTeachVo;
import com.ruoyi.classai.domain.vo.LearningAnalytics.AnalyticsStuCountVo;
import com.ruoyi.classai.service.*;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.RemoteAiModelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.UUID;

/**
 * 课堂授课接口
 * @author lcj
 * @date 2025年03月05日 15:14
 */
@Slf4j
@Validated
@RestController
@Tag(name = "课堂授课接口")
@RequestMapping("/api/courseteach")
public class CourseTeachApi {

    @Autowired
    private IEwcGroupingStrategyCodeService groupingStrategyCodeService;

    @Autowired
    private IEwcCourseGroupingService courseGroupingService;

    @Autowired
    private IEwcClassService classService;

    @Autowired
    private IEwcAttendanceRecordsService attendanceRecordsService;

    @Autowired
    private LearningStatisticsService learningStatisticsService;

    @Autowired
    private IEwcChapterService iEwcChapterService;

    @Autowired
    private IEwcAiTemplateService  ewcAiTemplateService;

    @Autowired
    private RemoteAiModelService remoteAiModelService;

    @Autowired
    private IEwcCourseplanService iEwcCourseplanService;
    /**
     * 查询分组策略
     * @return 分组策略列表
     */
    @Operation(summary = "查询分组策略")
    @GetMapping("/getGroupStrategy")
    public AjaxResult getGroupStrategy(){
        return AjaxResult.success(groupingStrategyCodeService.list());
    }


    /**
     * 添加分组
     * @return  AjaxResult
     */
    @Operation(summary = "添加分组")
    @PostMapping("/addGroup")
    public AjaxResult addGroup(@Valid @RequestBody GroupDto groupDto){
        courseGroupingService.addGroup(groupDto);
        return AjaxResult.success("添加成功");
    }

    /**
     * 查询分组班级详情
     * @return  AjaxResult
     */
    @Operation(summary = "查询分组班级详情")
    @GetMapping("/getGroupClassInfo")
    public AjaxResult getGroupClassInfo(@NotBlank(message = "班级id不能为空")String classId){

        return AjaxResult.success("查询成功", classService.getGroupClassInfo(classId));
    }

    /**
     * 查询分组列表
     * @param groupListDto 查询信息
     * @return  AjaxResult
     */
    @Operation(summary = "查询分组列表")
    @PostMapping("/getGroupList")
    public AjaxResult getGroupList(@Valid @RequestBody GroupListDto groupListDto){

        return AjaxResult.success("查询成功", courseGroupingService.getGroupList(groupListDto));
    }


    /**
     * 分组调整
     * @param groupingId 分组id
     * @param moveGroupingId 移动分组id
     * @param studentId 学生ID
     * @param sort 移动
     * @param groupingName 分组名称
     * @return AjaxResult
     */
    @Operation(summary = "分组调整")
    @GetMapping("/getGroupAdjust")
    public AjaxResult getGroupAdjust(@NotBlank(message = "分组id不能为空")String groupingId,
                                     @NotBlank(message = "分组id不能为空")String moveGroupingId,
                                     @NotBlank(message = "学生id不能为空")String studentId,
                                     @NotNull(message = "排序不能为空")Integer sort,
                                     @NotBlank(message = "分组不能为空")String groupingName){
        courseGroupingService.getGroupAdjust(groupingId, moveGroupingId,studentId,sort,groupingName);
        return AjaxResult.success("查询成功" );
    }

    /**
     * 查询课堂考勤
     * @param courseId 课程id
     * @param chapterId 章节id
     * @param classId 班级id
     * @return AjaxResult
     */
    @Operation(summary = "查询课堂考勤")
    @GetMapping("/getCourseAttendance")
    public AjaxResult getCourseAttendance(@NotBlank(message = "课程ID不能为空")String courseId,
                                     @NotBlank(message = "章节id不能为空")String chapterId,
                                          @NotBlank(message = "班级id不能为空")String classId){

        return AjaxResult.success("查询成功" ,attendanceRecordsService.getCourseAttendance(courseId,chapterId,classId));
    }

    /**
     * 添加删除课堂考勤
     * @param courseAttendanceDto 考勤信息
     * @return AjaxResult
     */
    @Operation(summary = "添加删除课堂考勤")
    @PostMapping("/addOrDelCourseAttendance")
    public AjaxResult addOrDelCourseAttendance(@Valid @RequestBody CourseAttendanceDto courseAttendanceDto){
        attendanceRecordsService.addOrDelCourseAttendance(courseAttendanceDto);
        return AjaxResult.success("添加成功");
    }

    /**
     * 学情分析页面查询接口
     * @param courseId 考勤信息
     * @param chapterId 考勤信息
     * @param classId 考勤信息
     * @return AjaxResult
     */
    @Operation(summary = "学情分析页面查询接口")
    @GetMapping("/getLearningStatisticsInfo")
    public AjaxResult getLearningStatisticsInfo(@NotBlank(message = "课程ID不能为空")String courseId,
                                                @NotBlank(message = "章节id不能为空")String chapterId,
                                                @NotBlank(message = "班级id不能为空")String classId){
        AjaxResult ajaxResult = learningStatisticsService.getLearningStatisticsInfo(courseId,chapterId,classId);
        if (ajaxResult.isSuccess()){
            return ajaxResult;
        }
        return AjaxResult.error("查询失败");
    }

    /**
     * 更新课时状态
     * @param ewcChapter 课时状态标识
     * @return AjaxResult
     */
    @Operation(summary = "更新课时状态")
    @PostMapping("/updateChapterStatus")
    public AjaxResult updateChapterStatus(@RequestBody EwcChapter ewcChapter){
        boolean result = iEwcChapterService.updateChapterStatus(ewcChapter);
        //更新授课状态为已授课时，生成本节课的课堂反思
        if(ewcChapter.getStatus() == 3){
            //查模板
            String msgTemplate = String.valueOf(ewcAiTemplateService.getById("generateLessonPlanInfo-courseBack_reflection"));
            if (msgTemplate != null) {
                //查询章节授课信息
                AnalyticsChapterTeachVo analyticsChapterTeachVo = iEwcChapterService.getChapterTeachInfo(ewcChapter);
                StringBuffer completedContent = new StringBuffer();
                if (!(analyticsChapterTeachVo.getSubjectMatter() == null)&& (!analyticsChapterTeachVo.getSubjectMatter().isEmpty())) {
                    completedContent.append("课时主题:").append(analyticsChapterTeachVo.getSubjectMatter()).append("、");
                }
                if (!(analyticsChapterTeachVo.getLearningGoal() == null) && (!analyticsChapterTeachVo.getLearningGoal().isEmpty())) {
                    completedContent.append("学习目标:").append(analyticsChapterTeachVo.getLearningGoal()).append("、");
                }
                if (!(analyticsChapterTeachVo.getTeachingFocus() == null) && (!analyticsChapterTeachVo.getTeachingFocus().isEmpty())) {
                    completedContent.append("教学重点:").append(analyticsChapterTeachVo.getTeachingFocus()).append("、");
                }
                if (!(analyticsChapterTeachVo.getDifficultPoints() == null) && (!analyticsChapterTeachVo.getDifficultPoints().isEmpty())) {
                    completedContent.append("教学难度:").append(analyticsChapterTeachVo.getDifficultPoints()).append("、");
                }
                if (analyticsChapterTeachVo.getGroupNumber() != 0) {
                    completedContent.append("分组个数:").append(analyticsChapterTeachVo.getGroupNumber()).append("、");
                }
                if (!(analyticsChapterTeachVo.getAverageScore() == null) && (!analyticsChapterTeachVo.getAverageScore().isEmpty()) ) {
                    completedContent.append("班级平均分:").append(analyticsChapterTeachVo.getAverageScore()).append("、");
                }
                if (!(analyticsChapterTeachVo.getStandardDeviation() == null) && (!analyticsChapterTeachVo.getStandardDeviation().isEmpty())) {
                    completedContent.append("标准差:").append(analyticsChapterTeachVo.getStandardDeviation()).append("、");
                }
                completedContent.append("学生举手总次数:").append(analyticsChapterTeachVo.getRaiseHandTotalCount()).append("、");
                // 替换模板中的变量
                String prompt = msgTemplate
                        .replace("@className@", analyticsChapterTeachVo.getClassName())
                        .replace("@studentCount@", analyticsChapterTeachVo.getStudentNum())
                        .replace("@course@", analyticsChapterTeachVo.getCourseName())
                        .replace("@capter@", analyticsChapterTeachVo.getChapterName())
                        .replace("@completedContent@", completedContent);

                // 调用AI服务
                log.info("调用ai接口，上送内容："+prompt);
                String aiResponse=remoteAiModelService.chat(prompt, String.valueOf(UUID.randomUUID()));
                log.info("ai接口返回内容："+aiResponse);
                int startIndex = aiResponse.indexOf("{");
                int endIndex = aiResponse.lastIndexOf("}") + 1;
                aiResponse = aiResponse.substring(startIndex, endIndex);
                String content = aiResponse.split(":")[1].trim(); // 按 `:` 分割，取第二部分
                content = content.replaceAll("^[^a-zA-Z0-9\\u4e00-\\u9fa5]+", "")
                                 .replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]+$", "");
                log.info("内容："+content);
                iEwcCourseplanService.updateReflection(ewcChapter,content);
            }
        }

        if (result) {
            return AjaxResult.success("更新成功");
        } else {
            return AjaxResult.error("更新失败");
        }
    }

}
